<template>
	<view class="page">
		<!-- #ifdef H5 -->
		<topVue title="AI视频创作" :isBack="true" rightIcon="server-fill"></topVue>
		<!-- #endif -->

		<view class="main-content">
			<scroll-view class="content" scroll-y>
				<view class="h2">上传视频</view>
				<view class="tip margin20">上传视频大小不超过100M， 时长不超过60秒！</view>
				<view class="uploadVue margin30 flex-center">
					<view class="upload" @click="chooseVideo()">点击上传视频</view>
				</view>
				<view class="h2 margin40">选择视频</view>
				<view class="uploadBox margin20 flex-between">
					<scroll-view class="scroll-view_H relative" scroll-x="true">
						<view class="w100 flex-column align-center padding-column20 absolute-auto"
							v-if="videoList.length===0">
							<image src="../../static/empty.png" style="width: 188rpx; height: 188rpx;"></image>
							<text style="color: #81868e;">当前列表为空</text>
						</view>
						<view class="upload" v-for="(item, i) in videoList" :key="i">
							<view class="videoVue relative">
								<image src="../../static/play.png" style="width: 60rpx; height: 60rpx;z-index: 99;" class="absolute-auto" @click="playVideo(item.videoUrl)"></image>
								<image :src="item.videoUrl+'?x-oss-process=video/snapshot,t_1,f_jpg,w_320,m_fast,ar_auto'" mode="aspectFill" style="width: 100%; height: 100%; border-radius: 12rpx;"></image>
							</view>
							<view class="bot flex-between align-center">
								<view class="btn" :class="{active: item.id===videoId}" @click="selectVideo(item)">使用</view>
								<view class="btn delete" @click="deleteId = item.id; show = true">删除</view>
							</view>
						</view>
					</scroll-view>
				</view>

				<!-- 设置视频名称 -->
				<view class="inpVue padding-column30 margin30">
					<view class="h2">设置视频名称</view>
					<input type="text" placeholder="请设置视频名称" v-model="name" />
				</view>

				<view class="h2">添加文案</view>
				<u-gap height="15"></u-gap>
				<u-subsection :list="tabs" :current="current" button-color="#3B82F6" active-color="#fff" bg-color="#F3F4F6" @change="change"></u-subsection>
				<textarea placeholder="请输入音频文案" v-if="current===0" maxlength="500" v-model="text"></textarea>

				<template v-if="current===1">
					<view class="uploadVue margin30 flex-center">
						<view class="upload" @click="chooseAudio()">点击上传音频</view>
					</view>
					<view class="inpVue padding-column30" v-if="voiceFileName && voiceFileUrl">
						<view class="h2">当前上传音频</view>
						<view class="flex-between">
							<audio :src="voiceFileUrl" :name="voiceFileName" controls></audio>
							<u-icon name="close" color="#81868e" size="30" @click="voiceFileName = ''; voiceFileUrl = ''"></u-icon>
						</view>
					</view>
				</template>

				<view class="flex align-center" v-if="current===2">
					<textarea placeholder="请输入音频文案需求" style="flex: 1;" v-model="aiText"></textarea>
					<view class="aiBtn text-center"
						style="width: 100rpx; height: 52rpx; line-height: 52rpx; color: #fff; background: #6AA1F8; border-radius: 12rpx; font-size: 24rpx;margin-left: 20rpx;"
						@click="aiBtnFun()">Ai生成</view>
				</view>

				<!-- 选择音色 -->
				<template v-if="current!=1">
					<view class="flex-between" style="padding-top: 20rpx;">
						<view class="h2">选择音色</view>
						<text style="color: #6AA1F8; text-decoration: underline;" @click="$tools.route('./voice')">去训练</text>
					</view>
					<view class="inpBox flex-between align-center" @click="show20 = true">
						<view v-if="voiceName">{{ voiceName }}-{{ voiceSex }}</view>
						<view v-else>请选择音色</view>
						<image src="../../static/more.png" style="width: 36rpx; height: 36rpx;"></image>
					</view>
				</template>

				<!-- 选择生成视频画质 -->
				<view class="inpVue padding-column30">
					<view class="label">选择生成视频画质（请注意，高清生成速度较慢）</view>
					<view class="radioVue flex-between align-center">
						<view class="flex align-center">
							<view class="radio flex align-center" @click="videoType=0">
								<image src="../../static/radio0.png" style="width: 48rpx; height: 48rpx;" v-if="videoType===1"></image>
								<image src="../../static/radio1.png" style="width: 48rpx; height: 48rpx;" v-if="videoType===0"></image>
								<view class="sex">标清</view>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 是否生成字幕 -->
				<view class="inpVue margin30">
					<view class="label">是否生成字幕</view>
					<view class="margin20">
						<u-radio-group v-model="word" active-color="#6917ED">
							<u-radio  v-for="(item, index) in words" :key="index"  :name="item.name">{{item.name}}</u-radio>
						</u-radio-group>
					</view>
				</view>

				<view class="text-center margin0" style="color: #888;">目前剩余{{ aiVideoPoints }}积分</view>

				<view class="startBtn margin20" @click="startFun()">开始生成视频</view>

				<view class="tipVue flex align-center margin20">
					<u-checkbox v-model="checked" active-color="#6917ED" label-size="24">公开训练后声音，可获得100积分用于合成视频</u-checkbox>
				</view>
			</scroll-view>
		</view>

		<!-- 删除视频 -->
		<u-modal v-model="show" content="确认删除该视频" :show-cancel-button="true" @confirm="deleteFun"></u-modal>

		<!-- 播放视频 -->
		<myVideo ref="myVideo" v-show="isPlay" @quit="isPlay = false"></myVideo>

		<!-- 选择音色 -->
		<u-popup v-model="show20" mode="left">
			<view class="popupVue">
				<view class="h2">选择音色</view>
				<view class="w100" style="padding: 15rpx 0 10rpx 0;">
					<u-subsection :list="tabList" :current="voiceCurrent" :button-color="buttonColor" height="80" active-color="#fff" bg-color="#F3F4F6" @change="voiceChange"></u-subsection>
				</view>

				<scroll-view scroll-y class="voiceVue">
					<view class="w100 flex-column align-center padding-column20 absolute-auto" v-if="list.length===0">
						<image src="../../static/empty.png" style="width: 250rpx; height: 250rpx;"></image>
						<text style="color: #81868e;">当前列表为空</text>
					</view>
					<view class="tabItem flex-between align-center" v-for="(item, index) in list" :key="index">
						<audio :src="item.url" :name="`${item.name}-${item.sex}`" controls></audio>
						<view class="select" @click.stop="chooseVoice(item)"></view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import myVideo from "@/components/myVideo.vue"
	import { mapState } from "vuex"
	import baseUrl from "@/common/url.js"
	export default {
		components: {
			myVideo
		},
		data() {
			return {
				radio: 0,
				checked: false,
				current: 0,
				voiceCurrent: 0,
				tabs: [{ name: "文本添加" }, { name: "音频添加" }, { name: "AI生成文案" }],
				tabList: [{ name: "我的" }, { name: "推荐" }, { name: "他人" }],
				list: [],
				videoList: [],
				name: "",
				text: "",
				uploadVideoUrl: "",
				videoId: "",
				videoType: 0,
				soundOriginalText: "",
				aiText: "",
				voiceFileName: "",
				voiceFileUrl: "",
				aiVideoPoints: 0,
				points: 0,
				show: false,
				deleteId: "",
				isPlay: false,
				show20: false,
				voiceType: "我的",
				voiceName: "",
				voiceSex: "",
				buttonColor: "linear-gradient(to right, #49DC83, #3B83F4)",
				words: [{name: "是"}, {name: "否"}],
				word: "是",
			}
		},
		async onLoad() {
			await this.getList()
			await this.getVideoList()
			await this.getPoint()
		},
		computed: {
			...mapState({
				user: state => state.user
			})
		},
		methods: {
			change(e) {
				this.current = e
			},
			voiceChange(e) {
				this.voiceType = this.tabList[e].name
				this.getList()
			},

			playVideo(videoUrl){
				this.isPlay = true
				this.$refs.myVideo.videoPlay(videoUrl)
			},

			async deleteFun(){
				const res = await this.$request("/shuziren/userUploadVideo", {
					id: this.deleteId
				}, "DELETE")
				if(res.code===200) {
					this.$u.toast("删除成功")
					this.getVideoList()
				}
			},

			// 获取积分
			async getPoint() {
				const res = await this.$request("/aiet-user-center/user/points/summary", {}, "GET")
				if (res.code === 200) {
					this.aiVideoPoints = res.data.aiVideoPoints
				}
			},

			async aiBtnFun() {
				if (!this.aiText) return this.$u.toast("请输入文案需求")
				uni.showLoading()
				const res = await this.$request("/shuziren/aichat/answer", {
					applicationId: "348f9058-8780-11ef-8828-0242ac110002",
					question: this.aiText
				})
				if (res.code === 200) {
					console.log(res)
					uni.hideLoading()
					this.aiText = res.data
				} else {
					uni.hideLoading()
					this.$u.toast(res.msg)
				}
			},

			// 选择声音
			chooseAudio() {
				let that = this
				uni.chooseFile({
					count: 1,
					extension: [".wav", ".mp3", ".m4a", ".amr"],
					success(res) {
						let fileName = res.tempFiles[0].name
						if(!fileName.endsWith(".wav") && !fileName.endsWith(".mp3") && !fileName.endsWith("m4a") && !fileName.endsWith("amr")) return that.$u.toast("请选择音频文件")
						console.log(res)
						let tempFilePaths = res.tempFilePaths[0]
						uni.showLoading()
						uni.uploadFile({
							url: baseUrl.url + "/aiet-file-center/file",
							filePath: tempFilePaths,
							name: "file",
							formData: {
								"path": "shuziren/audio"
							},
							success(uploadRes) {
								uni.hideLoading()
								let data = JSON.parse(uploadRes.data)
								if (data.code === 200) {
									console.log(data.data.fileUrl)
									that.voiceFileName = data.data.fileUrl.split("/")[data.data
										.fileUrl.split("/").length - 1]
									that.voiceFileUrl = data.data.fileUrl
									that.$u.toast("上传成功")
								} else {
									that.$u.toast(data.msg)
								}
							},
							fail(uploadError) {
								console.log(uploadError)
								uni.hideLoading()
								that.$u.toast("上传失败")
							}
						})
					}
				})
			},

			// 选择音色
			chooseVoice(item) {
				console.log("jjjjj")
				console.log(item)
				this.voiceName = item.name
				this.voiceSex = item.sex
				this.soundUrl = item.url
				this.soundOriginalText = item.soundText
				this.show20 = false
			},

			selectVideo(item) {
				if (this.videoId === item.id) return this.videoId = ""
				this.videoId = item.id
				this.uploadVideoUrl = item.videoUrl
			},

			// 开始生成视频第一步
			async startFun() {
				if (this.aiVideoPoints < 30) return this.$u.toast("积分不足，请充值")
				if (!this.name) return this.$u.toast("请设置视频名称")
				if (!this.uploadVideoUrl) return this.$u.toast("请选择视频")
				if (this.current===0 && !this.text) return this.$u.toast("请输入音频文案")
				if (this.current!=1 && !this.soundUrl) return this.$u.toast("请选择音色")
				if(this.current===1 && !this.voiceFileUrl) return this.$u.toast("请添加音频")
				uni.showLoading()
				const res = await this.$request("/shuziren/userVideo/startAudio", {
					name: this.name,
					publiced: this.checked,
					uploadVideoUrl: this.uploadVideoUrl,
					kouXing: -10,
					soundUrl: [this.soundUrl, this.voiceFileUrl, this.soundUrl][this.current],
					flagHd: this.videoType,
					soundText: [this.text, "", this.aiText][this.current],
					soundOriginalText: this.soundOriginalText,
					type: this.current===1 ? 1 : 2,
					subtitle: this.word==="是" ? 1 : 0
				}, "POST", "application/json")
				if (res.code === 200) {
					if (res.data.points > this.aiVideoPoints) return this.$u.toast(`生成此视频需要花费${res.data.points}积分，当前积分不足`)
					// 扣除积分
					this.$request("/aiet-user-center/user/points/subtract", {
						userId: this.user.id,
						points: res.data.points,
						type: "AI_VIDEO",
						action: "SUBTRACT"
					}, "POST", "application/json").then(result => {
						if (result.code === 200) {
							this.getPoint()
							this.startVideoFun(res.data)
						}else{
							uni.hideLoading()
							this.$u.toast(result.msg)
						}
					})
				} else {
					uni.hideLoading()
					this.$u.toast(res.msg)
				}
			},

			// 开始生成视频第三步
			startVideoFun(data) {
				this.$request("/shuziren/userVideo/startVideo", data, "POST", "application/json").then(res => {
					uni.hideLoading()
					if(res.code===200) {
						this.name = ""
						this.soundUrl = ""
						this.soundOriginalText = ""
						this.voiceFileUrl = ""
						this.text = ""
						this.aiText = ""
						this.checked = false
						this.voiceName =""
						this.voiceSex = ""
						this.$u.toast("生成视频已开始，请稍后查看")
					}else{
						this.$u.toast(res.msg)
					}
				})
			},

			// 获取音色列表
			async getList() {
				const res = await this.$request("/shuziren/soundTrain/list", {
					type: this.voiceType,
					pageNum: 0,
					pageSize: 100
				}, "GET")
				if (res.code === 200) this.list = res.data.content
			},

			// 获取上传视频列表
			async getVideoList() {
				const res = await this.$request("/shuziren/userUploadVideo", {
					pageNum: 0,
					pageSize: 30
				}, "GET")
				if (res.code === 200) {
					this.videoList = res.data.content
				}
			},

			// 保存视频
			keepVideo(data) {
				this.$request("/shuziren/userUploadVideo/add", {
					videoUrl: data.fileUrl,
					coverUrl: data.coverUrl
				}, "POST", "application/json").then(res => {
					if (res.code === 200) {
						console.log("保存视频成功")
						this.getVideoList()
					}
				})
			},

			// 上传视频
			chooseVideo() {
				let that = this
				uni.chooseVideo({
					type: "video",
					success(res) {
						console.log("视频大小：", res.size/1024/1024, "视频时长：", res.duration)
						if(res.size/1024/1024>100) return that.$u.toast("视频大小不得超过100M")
						if(res.duration>60) return that.$u.toast("视频时长不得超过60秒")
						let tempFilePath = res.tempFilePath
						console.log(tempFilePath)
						uni.showLoading()
						uni.uploadFile({
							url: baseUrl.url + "/aiet-file-center/file",
							filePath: tempFilePath,
							name: "file",
							formData: {
								"path": "shuziren/video"
							},
							success(uploadRes) {
								uni.hideLoading()
								let data = JSON.parse(uploadRes.data)
								console.log(data)
								if (data.code === 200) {
									that.$u.toast("上传成功")
									// 保存视频
									that.keepVideo(data.data)
								} else {
									that.$u.toast(data.msg)
								}
							},
							fail(uploadError) {
								console.log(uploadError)
								uni.hideLoading()
								that.$u.toast("上传失败")
							}
						})
					}
				})
			},

			// 计算需要多少个30
			calculatePoints(time) {
				// 每30秒等于30的积分
				let pointsPer100Units = 30;
				// 计算总共的30秒
				let hundredBlocks = Math.ceil(time / 30);
				// 计算总积分
				return hundredBlocks * pointsPer100Units;
			},
		}
	}
</script>

<style lang="less" scoped>
	/deep/ .uni-audio-default {
		max-width: 580rpx;
		height: 88rpx;
		min-width: 480rpx;
		margin-top: 10rpx;
	}
	/deep/ .uni-audio-left {
		width: 88rpx;
		height: 88rpx;
	}
	/deep/ .uni-audio-right {
		margin-left: 0;
		height: 88rpx;
	}
	/deep/ .uni-audio-button {
		width: 40rpx;
		height: 40rpx;
		margin: 24rpx
	}
	.main-content {
		width: 100%;
		height: calc(100vh - var(--window-bottom) - var(--window-top) - 92rpx);
		padding: 30rpx;
		box-sizing: border-box;
		background: linear-gradient(to bottom, #10B981, #3B82F6);
		.content {
			width: 100%;
			height: 100%;
			background: #fff;
			border-radius: 12rpx;
			padding: 30rpx;
			box-sizing: border-box;

			.h2 {
				font-weight: 700;
				font-size: 30rpx;
				color: #000;
			}

			.tip {
				font-size: 26rpx;
				color: #959496;
			}

			.uploadVue {
				width: 100%;
				height: 88rpx;
				color: #fff;
				text-align: center;
				line-height: 88rpx;
				border-radius: 44rpx;
				.upload {
					width: 100%;
					height: 88rpx;
					color: #fff;
					text-align: center;
					line-height: 88rpx;
					background: linear-gradient(to bottom, #10B981, #3B82F6);
					border-radius: 44rpx;
					font-size: 30rpx;
				}
			}

			.uploadBox {
				width: 100%;
				height: 588rpx;

				.scroll-view_H {
					width: 100%;
					height: 588rpx;
					white-space: nowrap;

					.upload {
						width: 350rpx;
						height: 588rpx;
						display: inline-block;
						border-radius: 10rpx;
						margin-right: 30rpx;
						border-radius: 12rpx;
						.videoVue {
							width: 350rpx;
							height: 508rpx;
						}
						.bot {
							width: 100%;
							height: 60rpx;
							line-height: 60rpx;
							text-align: center;
							border-radius: 0 0 12rpx 12rpx;
							font-size: 24rpx;
							margin-top: 20rpx;
							.btn {
								width: 45%;
								height: 56rpx;
								line-height: 56rpx;
								text-align: center;
								background: #ccc;
								font-size: 24rpx;
							}
							.delete {
								background: linear-gradient(to right, #49DC83, #3B82F6);
							}
							.active {
								background: linear-gradient(to right, #EAB108, #F87415);
								color: #fff;
							}
						}
					}
					.upload:nth-last-child(1) {
						margin-right: 0;
					}
				}
			}

			textarea {
				width: 100%;
				height: 160rpx;
				border-radius: 12rpx;
				background: #F3F4F6;
				font-size: 28rpx;
				padding: 15rpx;
				margin-top: 15rpx;
			}

			.inpBox {
				width: 100%;
				height: 88rpx;
				border: 1rpx solid #EBEDED;
				border-radius: 10rpx;
				padding: 0 20rpx;
				margin-top: 12rpx;
				input {
					font-size: 28rpx;
					flex: 1;
				}
			}

			.inpVue {
				width: 100%;
				.label {
					font-weight: 600;
					font-size: 28rpx;
				}
				.sudioVue {
					width: 100%;
					height: 88rpx;
					border: 1rpx solid #EBEDED;
					border-radius: 10rpx;
					padding: 0 20rpx;
					margin-top: 12rpx;
					text {
						color: #333;
						padding-left: 10rpx;
					}
				}

				input {
					width: 100%;
					height: 88rpx;
					border: 1rpx solid #F3F4F6;
					border-radius: 10rpx;
					display: block;
					margin-top: 12rpx;
					padding-left: 20rpx;
					font-size: 28rpx;
				}
			}

			.radioVue {
				width: 100%;
				.radio {
					height: 80rpx;
					margin-right: 20rpx;
				}
			}

			.tabItem {
				width: 100%;
				height: 80rpx;
				background: #F3F4F6;
				margin-top: 15rpx;
				border-radius: 12rpx;
				position: relative;
			}

			.tabActive {
				background: #4D82EF;
			}

			.startBtn {
				width: 100%;
				height: 88rpx;
				background: linear-gradient(to right, #49DC81, #3B84F2);
				border-radius: 12rpx;
				line-height: 88rpx;
				text-align: center;
				color: #fff;
				font-size: 30rpx;
			}
		}
	}
	.popupVue {
		width: 550rpx;
		padding: 30rpx;
		.h2 {
			font-weight: 700;
			font-size: 30rpx;
			color: #000;
		}
		.radio {
			height: 80rpx;
			margin-right: 30rpx;
		}
		.voiceVue {
			width: 100%;
			height: calc(100vh - 220rpx);
			.tabItem {
				width: 100%;
				height: 88rpx;
				position: relative;
				margin-bottom: 15rpx;
				.select {
					width: calc(100% - 88rpx);
					height: 88rpx;
					position: absolute;
					right: 0;
					top: 0;
					z-index: 999;
				}
			}
		}
	}
</style>
